package com.itheima.web.filter;

import com.itheima.domain.system.User;
import com.itheima.service.system.UserService;
import com.itheima.service.system.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(value = "/*")
public class AutoFilter implements Filter {
    private FilterConfig filterConfig;
    private UserService userService=new UserServiceImpl() ;

    /**
     * 初始化方法，获取过滤器的配置对象
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {/*
        HttpServletRequest request ;
        HttpServletResponse response;
        request = (HttpServletRequest)req;
        response = (HttpServletResponse)resp;
        String username;
        String password;
        //获取请求中的cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if("user".equals(cookie.getName())){
                    String value = cookie.getValue();
                    String[] sArr = value.split("&");
                    if (sArr.length == 2) {
                        username = sArr[0];
                        password = sArr[1];
                        User user=new User();
                        user.setUsername(username);
                        user.setPassword(password);
                        request.getSession().setAttribute("loginUser", user);
                        chain.doFilter(request,response);
                    }
                }
            }
        }*/
        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse)resp;
        //为了避免重复执行自动登录的逻辑，需要判断session中是否已经有loginUser
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if(loginUser!=null){
            //证明已经登录过了,直接放行
            chain.doFilter(request,response);
            return;
        }
        //登录相关的请求，直接放行
        String url = request.getRequestURI();
        if(url.contains("login")
        ||url.endsWith(".css")
                || url.endsWith(".js")
                || url.endsWith(".html")
                || url.endsWith(".png")
                || url.endsWith(".jpg")
                || url.endsWith("index.jsp")
                || url.endsWith("unauthorized.jsp")
                || url.endsWith("login.jsp")
                || url.endsWith("alertPassword.jsp")
                || url.endsWith("favicon.ico")){
            chain.doFilter(request,response);
            return;
        }
        //
        String queryString = request.getQueryString();
        if(queryString==null
                ||queryString.endsWith("operation=login")
                ||queryString.endsWith("operation=home")
                ||queryString.endsWith("operation=logout")
                ||queryString.endsWith("operation=toLogin")
                ||queryString.endsWith("operation=changePwd")){
            chain.doFilter(request,response);
            return;
        }
        String cookieValue=null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if("user".equals(cookie.getName())){
                    cookieValue=cookie.getValue();
                    break;
                    }
                }
            }
        boolean isLogin=false;
        //校验cookie中的value
        if(cookieValue!=null){
            String[] sArr = cookieValue.split("&");
            String username=sArr[0];
            String password=sArr[1];
            //校验用户名密码
            User user=userService.login(username,password);
            if(user!=null){
                //校验成功，保存用户的登录信息
                HttpSession session = request.getSession();
                session.setAttribute("loginUser",user);
                //自动登录成功修改标记
                isLogin=true;

            }
        }

        //判断自动登录是否成功
        if(isLogin){
            chain.doFilter(request,response);
        }else{
            //验证失败，跳转到登录界面
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }


    }

    @Override
    public void destroy() {

    }
}
